"use strict";

var dappAddress = "n21n6vuTPK1mdYgd933tWA8QyVMSzeUseEJ";
var hash = "473d1626022e7bb13087f78c535a8ab8727ca34491e608b801efb9549421c92f";
var NebPay = require("nebpay");
var nebPay = new NebPay();
var html = '';

if (typeof webExtensionWallet === "undefined") {
  layer.msg('星云钱包环境未运行，请安装钱包插件')
}

nebPay.simulateCall(dappAddress, "0", "get", JSON.stringify([]), {
    listener: function(res) {
      if(res.result == '' && res.execute_err == 'contract check failed') {
          layer.msg('合约检测失败，请检查浏览器钱包插件环境！');
          return;
      }
      var datalist = JSON.parse(res.result);
      console.log(datalist);
      renderSearch(datalist)
    }
})

function renderSearch (data) {
  var datas = JSON.parse(data);
  console.log(datas);

  if (datas && datas.length) {
    var datalist = datas.sort(function (a, b) {
      var value1 = a.points,
          value2 = b.points;
      if(value1 === value2){
          return a.time - b.time;
      }
      return value2 - value1;
    })
    
    for (var i = 0; i < datalist.length; i++) {
      if (i < 20) {
        html += `<tr><td>${i+1}</td><td>${datalist[i].username}</td><td>${datalist[i].points}</td><td>${datalist[i].time}</td></tr>`
      }
    }
  } else {
    html += '<tr><td>暂无数据！</td></tr>'
  }
}


$('#ranking').click(function(){
  if(html){
    layer.open({
      type: 1,
      title: '排行榜前20',
      skin: 'layui-layer-rim',
      area: ['420px', '240px'], //宽高
      content: `<div id='rankList'><table><tr><th>名次</th><th>用户名</th><th>分数</th><th>耗时</th></tr>${html}</table></div>`
    });
  }else{
    layer.msg('正在加载中，请稍后再试');
  }
})

$('#upload').click(function(){
  layer.prompt(function(val,index){
    var usernameV = val;
    var pointsV = localStorage.getItem('last-points');
    var timeV = localStorage.getItem('last-time');
    layer.close(index);
    nebPay.call(dappAddress, "0", "set", JSON.stringify([{
      username: usernameV, 
      points: pointsV, 
      time: timeV
    }]), { 
      listener: function(res) {
        if (res.txhash) {
          layer.msg('信息存入需要一分钟，之后可刷新网页，查看排行榜');
        }
      }
    })
  });
})